package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.MyApplication
import cn.school.demo.pojo.Rank
import cn.school.demo.pojo.Result
import cn.school.demo.pojo.User
import cn.school.demo.util.HttpApi
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import kotlin.Error

class DataRepository {
    companion object {
        const val BASEURL = "http://120.53.123.145:8888/"
    }

    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(BASEURL).addConverterFactory(GsonConverterFactory.create())
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun isCF(userId: Int, articleId: Int): LiveData<Map<String, Boolean>> {
        val responseLiveData = MutableLiveData<Map<String, Boolean>>()
        httpApi.getArticleInformation(mapOf("sfNumber" to userId, "articleId" to articleId))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        if (it.data["fabulous"] != null && it.data["collect"] != null) {
                            try {
                                val fabulous = GsonUtils.fromJson<Boolean>(
                                    it.data["fabulous"].toString(),
                                    object : TypeToken<Boolean>() {}.type
                                )
                                val collect = GsonUtils.fromJson<Boolean>(
                                    it.data["collect"].toString(),
                                    object : TypeToken<Boolean>() {}.type
                                )
                                responseLiveData.value =
                                    mapOf("fabulous" to fabulous, "collect" to collect)
                            } catch (e: Error) {
                                LogUtils.e(e.printStackTrace())
                            }
                        } else {
                            LogUtils.e("是否收藏点赞http返回值的data的fabulous或collect为空！")
                        }
                    } ?: LogUtils.e("是否收藏点赞http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }

            })
        return responseLiveData
    }

    fun editUserInfo(user: User): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        val params = mapOf("user" to GsonUtils.toJson(user))
        httpApi.editUserInfo(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                LogUtils.d("修改个人信息http回调成功！")
                response.body()?.let {
                    responseLiveData.value = response.body()
                } ?: LogUtils.e("修改个人信息http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }

        })
        return responseLiveData
    }

    fun getCode(phone: String): LiveData<String> {
        val responseLiveData = MutableLiveData<String>()
        val params = mapOf("telephoneNumber" to phone)
        httpApi.getCode(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    when (it.success) {
                        true -> {
                            it.data["verificationCode"]?.let {
                                responseLiveData.value =
                                    response.body()!!.data["verificationCode"].toString()
                            } ?: LogUtils.d("获得验证码http返回值的data的verificationCode")
                        }
                        else -> LogUtils.d(response.body())
                    }
                } ?: LogUtils.e("获得验证码http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }

        })
        return responseLiveData
    }

    fun formUpdate(id: Int): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        try {
            //2.获取图片，创建请求体
            val file = File(MyApplication.imageUrl!!)
            val body =
                File(MyApplication.imageUrl!!).asRequestBody("image/*".toMediaTypeOrNull())
            val mbp: MultipartBody.Part = MultipartBody.Part.createFormData("head", file.name, body)
            httpApi.formUpload(id, mbp)
                .enqueue(object : Callback<Result> {
                    override fun onResponse(call: Call<Result>, response: Response<Result>) {
                        response.body()?.let {
                            responseLiveData.value = it
                        }
                    }

                    override fun onFailure(call: Call<Result>, t: Throwable) {
                        LogUtils.e(t)
                    }
                })
        } catch (e: Error) {
            LogUtils.e(e.printStackTrace())
        }
        return responseLiveData
    }

    fun getScoreRanking(id: Int): LiveData<MutableList<Rank>> {
        val responseLiveData = MutableLiveData<MutableList<Rank>>()
        httpApi.getScoreRanking(mapOf("signId" to id)).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    if (it.success) {
                        it.data["rank"]?.let { jsonData ->
                            try {
                                val map = GsonUtils.fromJson<MutableList<Rank>>(
                                    jsonData.toString(),
                                    object : TypeToken<MutableList<Rank>>() {}.type
                                )
                                responseLiveData.value = map
                            } catch (e: Error) {
                                LogUtils.e(e.printStackTrace())
                            }
                        } ?: LogUtils.e("获得答题分数排行榜http返回值的data[rank]为空！")
                    } else {
                        LogUtils.e(it.message)
                    }
                } ?: LogUtils.e("获得答题分数排行榜http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }
}